package com.xyzh05.webapp.action.android;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.LazyDynaBean;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.model.Department;
import com.xyzh05.model.Role;
import com.xyzh05.model.User;
import com.xyzh05.model.UserInfo;
import com.xyzh05.service.DictItemManager;
import com.xyzh05.service.UserInfoManager;
import com.xyzh05.util.JSONUtil;
import com.xyzh05.webapp.action.BaseAction;

/**
 * Action for facilitating User Management feature.
 */
public class UserAction extends BaseAction implements Preparable {
    private static final long serialVersionUID = 6776558938712115191L;
    
    private PasswordEncoder passwordEncoder;
    private UserInfoManager userInfoManager;
    private DictItemManager dictItemManager;
    private User user;
    private Role role;
    private UserInfo userInfo;
    private Department department;
    private Integer actionType;
    private Map<String, Object> jsonMap = new HashMap<String, Object>();


	public void prepare() throws Exception {		
	
	}
    
	/**
	 * 移动终端 - 用户注册
	 * @return
	 */
	public String UserRegister(){
		Boolean userExist = userManager.userExist(user.getEmail());
		if(userExist){
            jsonMap.put("status", "0");
            jsonMap.put("data", "");
            jsonMap.put("info", "");
            jsonMap.put("errorCode", "1001");
            return SUCCESS;
		}
    	if(actionType == 1){
    		department = new Department();
    		department.setDictItemByDeptTypeId(dictItemManager.get(Department.DEPARTMENT));
    		department.setDisplayName(user.getDisplayName());
    		
    		try {
    			department = departmentManager.save(department);				
			} catch (Exception e) {
	            jsonMap.put("status", "0");
	            jsonMap.put("data", "");
	            jsonMap.put("info", "");
	            jsonMap.put("errorCode", "1000");
				return SUCCESS;
			}
    		role = new Role();
    		role.setName(Role.ROLE_COMPANY);
    		role.setRoleType(dictItemManager.get(Role.DEFAULT_ROLE_COMPANY));
    		role.setDepartment(department);
			
    		try {
    			role = roleManager.save(role);				
			} catch (Exception e) {
	            jsonMap.put("status", "0");
	            jsonMap.put("data", "");
	            jsonMap.put("info", "");
	            jsonMap.put("errorCode", "1000");
				return SUCCESS;
			}
    		
    		user.setRoleId(role.getId());
    		user.addRole(role);
    		
    		userInfo.setDeptName(user.getDisplayName());
    		userInfo.setPhone(user.getMobilephone());
    		
    	}else{
    		user.addRole(roleManager.get(Role.DEFAULT_ROLE_USER));    		
    	}
    	
		user.setUsername(user.getEmail());
		user.setUserInfo(userInfo);
		userInfo.setUser(user);
		
		try {
			user = userManager.saveUser(user);
        } catch (Exception e) {
            log.warn(e.getMessage());
            jsonMap.put("status", "0");
            jsonMap.put("data", "");
            jsonMap.put("info", "");
            jsonMap.put("errorCode", "1000");
            return SUCCESS; 
        }

		LazyDynaBean ldb = new LazyDynaBean();
    	if(actionType == 1){
    		ldb.set("id", user.getId());
    		ldb.set("displayName", user.getDisplayName());
    		ldb.set("mobilephone", user.getMobilephone());
    		ldb.set("email", user.getEmail());
    		ldb.set("contact", user.getUserInfo().getContact());
    		ldb.set("communication", user.getUserInfo().getCommunication());
    	}else{
    		ldb.set("id", user.getId());
    		ldb.set("displayName", user.getDisplayName());
    		ldb.set("email", user.getEmail());
    		ldb.set("deptName", user.getUserInfo().getDeptName());    		
    	}
    	
        jsonMap.put("status", "1");
        jsonMap.put("data", JSONUtil.getMapFromJsonObjStr(JSONUtil.getJsonStr(ldb)));
        jsonMap.put("info", "");
        jsonMap.put("errorCode", "");
        return SUCCESS;
    }

	/**
	 * 移动终端 - 用户登录
	 * @return
	 */
    public String UserLogin(){
		try {
			user = userManager.loadUserByUsernameAndPassword(user.getUsername(), passwordEncoder.encodePassword(user.getPassword(), null));
			if(user != null){
				LazyDynaBean ldb = new LazyDynaBean();
	    		ldb.set("id", user.getId());
				ldb.set("displayName", user.getDisplayName());
				ldb.set("email", user.getEmail());
				ldb.set("deptName", user.getUserInfo().getDeptName());

		        jsonMap.put("status", "1");
		        jsonMap.put("data", JSONUtil.getMapFromJsonObjStr(JSONUtil.getJsonStr(ldb)));
		        jsonMap.put("info", "");
		        jsonMap.put("errorCode", "");
		        
		        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
		                user.getUsername(), user.getConfirmPassword(), user.getAuthorities());
		        auth.setDetails(user);
		        SecurityContextHolder.getContext().setAuthentication(auth);
			}else{
	            jsonMap.put("status", "0");
	            jsonMap.put("data", "");
	            jsonMap.put("info", "");
	            jsonMap.put("errorCode", "1000");
			}
		} catch (Exception e) {
            jsonMap.put("status", "0");
            jsonMap.put("data", "");
            jsonMap.put("info", "");
            jsonMap.put("errorCode", "1000");
		}
    	return SUCCESS;
    }
    
    public String UserEdit(){
    	try {
			User u = userManager.get(user.getId());
			u.setDisplayName(user.getDisplayName());
			u.setGender(user.getGender());
			u.setEmail(user.getEmail());
			u.setMobilephone(user.getMobilephone());
			u.getUserInfo().setDeptName(userInfo.getDeptName());
			u.getUserInfo().setProfession(userInfo.getProfession());
			u.getUserInfo().setPosition(userInfo.getPosition());
			u.getUserInfo().setPhone(userInfo.getPhone());
			u.getUserInfo().setCommunication(userInfo.getCommunication());
			
			userManager.saveOrUpdate(u);

	        jsonMap.put("status", "1");
	        jsonMap.put("data", "");
	        jsonMap.put("info", "");
	        jsonMap.put("errorCode", "");
		} catch (Exception e) {
            jsonMap.put("status", "0");
            jsonMap.put("data", "");
            jsonMap.put("info", "");
            jsonMap.put("errorCode", "1000");
		}
    	return SUCCESS;    	
    } 
    
	public UserInfoManager getUserInfoManager() {
		return userInfoManager;
	}

	public void setUserInfoManager(UserInfoManager userInfoManager) {
		this.userInfoManager = userInfoManager;
	}

	public DictItemManager getDictItemManager() {
		return dictItemManager;
	}

	public void setDictItemManager(DictItemManager dictItemManager) {
		this.dictItemManager = dictItemManager;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public Department getDepartment() {
		return department;
	}

	public void setDepartment(Department department) {
		this.department = department;
	}

	public Integer getActionType() {
		return actionType;
	}

	public void setActionType(Integer actionType) {
		this.actionType = actionType;
	}

	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public Map<String, Object> getJsonMap() {
		return jsonMap;
	}

	public void setJsonMap(Map<String, Object> jsonMap) {
		this.jsonMap = jsonMap;
	}
}
